#include "CellProcessor.h"
#include "Masyu3.h"
CellProcessor::~CellProcessor(void)
{
}

void CellProcessor::ProcessingLogic()
{
	cout<<"THREAD1: CellProcessor processing logic works\n";
	while (true)
	{
		while (!jobQ->empty())
		{
			pair<int, int> res;
			pair<Cell*, Cell*> mapres;		//for keeping addresses of neighbors returned from getMapObject
			Cell *tempCell = 0;
			cout<<"THREAD1: CP Q size: "<<jobQ->size()<<endl;
			{
				boost::lock_guard<mutex> lock(QmQMutex);
				tempCell = jobQ->back();
				jobQ->pop();
			}
			
			res = tempCell->checkDirectionSwitch(WHITE);
			if (1 == res.second) /*return 1*/ cout<<"ERROR 1\n";
			if (res.first != 0)		//It equals to condition != NOT
			{
				if (HALF == tempCell->getCondition())
				{
					//cout<<"THREAD1: whiteProcessing: HALF == getCondition"<<endl;
					if (tempCell->getDirection().num_blocked != 0) tempCell->setDirectionTo(res, BLOCKED);
					else if (tempCell->getDirection().num_free != 0) tempCell->setDirectionTo(res, FREE);
					else 
					{
						cout<<"THREAD1: Crap! HALF == tempCell->getCondition() returned crap!\n";
						cout<<"ERROR 2\n";
						/*return 1*/;
					}
				}

				if (READY == tempCell->getCondition())
				{
					//cout<<"THREAD1: whiteProcessing: READY == getCondition"<<endl;

					if (0 == tempCell->getDirection().num_blocked && tempCell->getDirection().num_free != 0)	//check that no blocked but there are free
					{
						res = tempCell->checkDirectionSwitch(WHITE);			//if so, we want to get borders to block, cuz there have to be blocked borders
						tempCell->setDirectionTo(res, BLOCKED);
					}
					if (tempCell->getDirection().num_blocked != 0) res = tempCell->checkDirectionSwitch(WHITE);		//so we got them and we get ...
							//...FREE now to set condition to neighbors
					mapres = getMapObject(objfinder(), tempCell, res);
				}
				else
				{
					cout<<"Looks like some shit happened here!!!\n";
					cout<<"ERROR 3\n";
							/*return 1;*/
				}
			}
			{
				boost::lock_guard<mutex> lock(QmQMutex);
				qmQ().push(mapres.first);
				if (mapres.second != 0)	qmQ().push(mapres.second);
				jobDone->notify_one();
			}
			cout<<"THREAD1: Lets notify in CellProcessor that jobDone\n";

								
		}
		boost::unique_lock<mutex> lock(CPMutex);
		doJob->wait(lock);
		
	}
}
